<?php

/**
 * Capital Direct Lending (http://www.philbsd.com/cdl)
 *
 * Copyright (C) 2008 Philippine Business Solution Developers <http://www.philbsd.com>
 * All rights reserved.
 *
 *
 * LICENSE
 *
 * This source file is subject to the GNU General Public License v3 license
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@philbsd.com so we can send you a copy immediately.
 *
 * @copyright  (c) 2008 Philippine Business Solution Developers. (http://www.philbsd.com)
 * @license    http://www.gnu.org/licenses/gpl-3.0.txt
 * @version    $Id: loan.php 161 2008-04-13 07:25:10Z artiskool $
 */

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Loan extends SB_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->_data['menuLoan'] = true;
		$this->load->model('Loans');
	}

	public function index()
	{
		$this->_data['msg'] = $this->session->flashdata('msg');
		$this->_data['records'] = $this->Loans->getAll();
		$this->render('loan/index.shtml');
	}

	public function add($page = 'page1')
	{
		$this->load->library('validation');

		if ($page == 'page1') {
			if (isset($_POST['next'])) {
				$rules['Loan/borrower_id'] = "required";
				$rules['Loan/coborrower_id'] = "required";
				$rules['Loan/inquiry_date'] = "required";
				$rules['Loan/application_date'] = "required";
				$rules['Loan/status'] = "required";
				$rules['Loan/collector_id'] = "required";
				$rules['Loan/pn_signed_date'] = "required";
				$rules['Loan/loan_type'] = "required";
				$rules['Loan/principal_amount'] = "required";
				$rules['Loan/interest_percentage'] = "required";
				$rules['Loan/loan_amount'] = "required";
				$rules['Loan/surcharges'] = "required";
				$rules['Loan/payment_days'] = "required";
				$rules['Loan/payment_scheme'] = "required";
				$rules['Loan/daily_due'] = "required";
				$rules['Loan/start_date'] = "required";
				$this->validation->set_rules($rules);

				$fields['Loan/borrower_id'] = 'Borrower ID';
				$fields['Loan/coborrower_id'] = "Co-borrower ID";
				$fields['Loan/inquiry_date'] = "Inquiry Date";
				$fields['Loan/application_date'] = "Application Date";
				$fields['Loan/status'] = "Loan Status";
				$fields['Loan/collector_id'] = "Collector ID";
				$fields['Loan/pn_signed_date'] = "Date PN Signed";
				$fields['Loan/loan_type'] = "Loan Type";
				$fields['Loan/principal_amount'] = "Principal";
				$fields['Loan/interest_percentage'] = "Interest (%)";
				$fields['Loan/loan_amount'] = "Total Loan Amount";
				$fields['Loan/surcharges'] = "Surcharges";
				$fields['Loan/payment_days'] = "Loan Payment (Days)";
				$fields['Loan/payment_scheme'] = "Payment Terms";
				$fields['Loan/daily_due'] = "Daily Due";
				$fields['Loan/start_date'] = "Loan Start Date";
				$this->validation->set_fields($fields);

				if ($this->validation->run()) {
					$valid_borrowers = true;
					$sql = "SELECT id FROM borrowers  WHERE id = '{$this->_swordPost['Loan']['borrower_id']}'";
					$result = $this->db->query($sql);
					if ($result->num_rows() <= 0) {
						$msg = "Borrower ID # {$this->_swordPost['Loan']['borrower_id']} does not exists.";

						if (isset($this->_data['msg'])) {
							$this->_data['msg'] .= "\n<br />$msg";
						} else {
							$this->_data['msg'] = $msg;
						}
						$valid_borrowers = false;
					}

					$sql = "SELECT id FROM borrowers  WHERE id = '{$this->_swordPost['Loan']['coborrower_id']}'";
					$result = $this->db->query($sql);
					if ($result->num_rows() <= 0) {
						$msg = "Coborrower ID # {$this->_swordPost['Loan']['borrower_id']} does not exists.";
						if (isset($this->_data['msg'])) {
							$this->_data['msg'] .= "\n<br />$msg";
						} else {
							$this->_data['msg'] = $msg;
						}
						$valid_borrowers = false;
					}

					if ($valid_borrowers) {
						$data = $this->_swordPost['Loan'];
						$this->session->set_userdata('Loan', $data);
						header("Location: {$this->_data['baseUrl']}loan/add/addpage2.html");
						exit;
					}
				}
			}
			$sql = "SELECT * FROM loan_matrix";
			$result = $this->db->query($sql);
			$this->_data['loan_matrix'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['loan_matrix'][] = $row;
				}
			}
			$this->render('loan/add.shtml');
		} else if ($page == 'addpage2') {
			$loan_info = $this->session->userdata('Loan');
			$this->_data['borrower_id'] = $loan_info['borrower_id'];
			$sql = "SELECT * FROM businesses WHERE borrower_id = '{$loan_info['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['businesses'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['businesses'][] = $row;
				}
			}
			$sql = "SELECT * FROM collaterals WHERE borrower_id = '{$loan_info['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['collaterals'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['collaterals'][] = $row;
				}
			}
			$sql = "SELECT * FROM notes WHERE borrower_id = '{$loan_info['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['notes'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['notes'][] = $row;
				}
			}
			if (isset($_POST['next'])) {
				header("Location: {$this->_data['baseUrl']}loan/add/addpage3.html");
				exit;
			}
			$this->render('loan/addpage2.shtml');
		} else if ($page == 'addpage3') {
			$this->_data['loan'] = $this->session->userdata('Loan');
			$sql = "SELECT * FROM profiles p RIGHT JOIN borrowers b ON p.id=b.profile_id  WHERE b.id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['borrower'] = array();
			if ($result->num_rows() > 0) {
				$this->_data['borrower'] = $result->row_array();
			}
			$sql = "SELECT * FROM profiles p RIGHT JOIN borrowers b ON p.id=b.profile_id  WHERE b.id = '{$this->_data['loan']['coborrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['coborrower'] = array();
			if ($result->num_rows() > 0) {
				$this->_data['coborrower'] = $result->row_array();
			}
			$sql = "SELECT * FROM businesses WHERE borrower_id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['businesses'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['businesses'][] = $row;
				}
			}
			$sql = "SELECT * FROM collaterals WHERE borrower_id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['collaterals'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['collaterals'][] = $row;
				}
			}
			$sql = "SELECT * FROM notes WHERE borrower_id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['notes'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['notes'][] = $row;
				}
			}
			if (isset($_POST['save_record'])) {
				$this->db->trans_begin();

				$data = $this->session->userdata('Loan');
				$this->db->insert('loans', $data);

				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$errMsg = "Failed to add!";
					if (isset($this->_data['msg'])) {
						$this->_data['msg'] .= $errMsg;
					} else {
						$this->_data['msg'] = $errMsg;
					}
				} else {
					$this->db->trans_commit();
					$this->session->set_flashdata('msg', "Successfully saved!");
					header("Location: {$this->_data['baseUrl']}loan.html");
					exit;
				}
			}
			$this->render('loan/addpage3.shtml');
		}
	}

	public function view($id)
	{
		$this->_data['record'] = $this->Loans->getLoan($id);
		$this->render('loan/view.shtml');
	}
    public function edit_loan($id)
	{
        $this->_data['record'] = $this->Loans->getLoan($id);
		$this->render('loan/edit_loan.shtml');
                                                     
        // editting loan
        if (isset($_POST['Loan/application_date'])) {

            $this->db->trans_begin();
		    $data = $this->_swordPost['Loan'];
			$this->db->where('id', $id);
            $this->db->update('loans', $data);
             $this->db->trans_commit();
             $this->session->set_flashdata('msg', "Successfully saved!");
             header("Location: {$this->_data['baseUrl']}/loan/view/{$id}.html");
			exit;
        }
	}

	public function borrower()
	{
		$this->render('loan/borrower.shtml');
	}

	public function coborrower()
	{
		$this->render('loan/coborrower.shtml');
	}

	public function business()
	{
		$this->render('loan/business.shtml');
	}

	public function collateral()
	{
		$this->render('loan/collateral.shtml');
	}

	public function note()
	{
		$this->render('loan/note.shtml');
	}
  
    public function edit_borrower()
	{
		$this->render('loan/edit_borrower.shtml');
	}
    public function edit_coborrower()
	{
		$this->render('loan/edit_coborrower.shtml');
	}
    public function edit_business()
	{
		$this->render('loan/edit_business.shtml');
	}
    public function edit_collateral()
	{
		$this->render('loan/edit_collateral.shtml');
	}

}
